﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace ViewMaker.Core.Silverlight
{
    public class DataGridDoubleClickBehavior : Behavior<DataGrid>
    {
        public static double DoubleClickDuration = 250;

        public DataGridDoubleClickBehavior()
        {

        }

        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(DataGridDoubleClickBehavior), new PropertyMetadata(CommandCallback));

        public ICommand Command
        {
            get { return (ICommand)this.GetValue(CommandProperty); }
            set { this.SetValue(CommandProperty, value); }
        }


        private static void CommandCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

        }
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.LoadingRow += new EventHandler<DataGridRowEventArgs>(AssociatedObject_LoadingRow);
            AssociatedObject.UnloadingRow += new EventHandler<DataGridRowEventArgs>(AssociatedObject_UnloadingRow);
        }

        void AssociatedObject_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseLeftButtonUp += new MouseButtonEventHandler(Row_MouseLeftButtonUp);
        }

        void AssociatedObject_UnloadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseLeftButtonUp -= new MouseButtonEventHandler(Row_MouseLeftButtonUp);
        }

        private DateTime lastClickTime;
        private DataGridRow lastClickRow;

        void Row_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (Command == null) return;
            DateTime now = DateTime.Now;
            if (lastClickRow == sender && now.Subtract(lastClickTime).TotalMilliseconds <= DoubleClickDuration)
            {
                var row = (DataGridRow)sender;
                
                Command.Execute(row.DataContext);
                lastClickRow = null;
            }
            else
            {
                lastClickRow = sender as DataGridRow;
                lastClickTime = now;
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.LoadingRow -= new EventHandler<DataGridRowEventArgs>(AssociatedObject_LoadingRow);
            AssociatedObject.UnloadingRow -= new EventHandler<DataGridRowEventArgs>(AssociatedObject_UnloadingRow);
        }



    }
}
